package eu.boss;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;

import eu.boss.model.StatsMessage;

@SuppressWarnings("serial")
public class UpdateStatsServlet extends HttpServlet {
	public static String SUCCESS = "SUCCESS";
	public static String FAILED = "FAILED";
	private DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	private ObjectMapper mapper = new ObjectMapper();

	
	/**
	 * Launch when put request
	 */
	@Override
	public void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		//UserName is used as kind suffix 
		String strStatsMsg, strPlayer, hash;
		StatsMessage statsMsg = new StatsMessage();

		resp.setContentType("text/plain");
		
		strStatsMsg = req.getParameter("statsMessage");
		hash= req.getHeader("User-Agent");
		
		if ((strStatsMsg != null)&&(hash!=null)) {
			
			//update playerList
			statsMsg = mapper.readValue(strStatsMsg, StatsMessage.class);
			
			Query query = new Query("PlayerList"+ hash);
			for (Entity entity : datastore.prepare(query).asIterable()) {
				datastore.delete(entity.getKey());
			}

			for (int i = 0; i < statsMsg.getPlayers().size(); i++) {
				strPlayer = mapper.writeValueAsString(statsMsg.getPlayers().get(i));
				Entity player = new Entity("PlayerList"+ hash);
				player.setProperty("playerList", strPlayer);
				datastore.put(player);
			}
			
			//update teamList
			
			Query query2 = new Query("TeamList"+ hash);
			for (Entity entity : datastore.prepare(query2).asIterable()) {
				datastore.delete(entity.getKey());
			}
			
			for (int j= 0; j<3; j++)
			{
				String strTeam = mapper.writeValueAsString(statsMsg.getTeams().get(j));
				Entity team = new Entity("TeamList"+ hash);
				team.setProperty("teamList", strTeam);
				datastore.put(team);
			}
			resp.getWriter().println(SUCCESS);
		} else
			resp.getWriter().println(FAILED);
	}
}
